package com.accp.hotevent.controller;

import com.accp.hotevent.entity.Comment;
import com.accp.hotevent.entity.Event;
import com.accp.hotevent.entity.User;
import com.accp.hotevent.req.AddEventRequest;
import com.accp.hotevent.req.EventListRequest;
import com.accp.hotevent.resp.CommonResp;
import com.accp.hotevent.service.EventService;
import com.accp.hotevent.util.LoggedUserContext;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/event")
@Slf4j
public class EventController {

    @Autowired
    private EventService eventService;

    @GetMapping("/one/{id}")
    public CommonResp<Event> getOne(@PathVariable("id") Integer id){
        CommonResp<Event> commonResp = new CommonResp<>();
        Event event = eventService.getOne(id);
        HashMap<String,Object> map = new HashMap<>();
        commonResp.setSuccess(true);
        commonResp.setData(event);
        return commonResp;
    }

    @GetMapping("/list")
    public CommonResp<PageInfo<Event>> getlist(EventListRequest request) {
        if (request.getPageNum() == null || request.getPageNum() <= 0) {
            request.setPageNum(1);
        }
        log.info("Entering index p:{} r:{} title:{}", request.getPageNum(), request.getPageSize(), request.getTitle());
        Event event = new Event();
        if(request.getTitle() != null) {
            event.setTitle(request.getTitle());
        }
        if(request.getUserId() != null) {
            event.setUser(User.builder().id(request.getUserId()).build());
        }
        PageInfo<Event> pageInfo = eventService.list(request);
        CommonResp<PageInfo<Event>> commonResp = new CommonResp<>();
        commonResp.setSuccess(true);
        commonResp.setData(pageInfo);
        return commonResp;
    }

    @PostMapping("/add")
    public CommonResp<Event> addEvent(@RequestBody AddEventRequest addEventRequest){
        User loggedUser = LoggedUserContext.getCurrentLoggedUser();
        if(loggedUser.isBanned()){
            throw new RuntimeException("该用户已被禁言");
        }
        CommonResp<Event> commonResp = new CommonResp<>();
        Event event = Event.builder()
                .title(addEventRequest.getTitle())
                .user(loggedUser)
                .content(addEventRequest.getContent())
                .searchIndex(addEventRequest.getSearchIndex())
                .approvalStatus("Pending")
                .build();
        eventService.add(event);
        commonResp.setSuccess(true);
        commonResp.setData(event);
        return commonResp;
    }
}
